package org.springblade.resource.config;

import io.minio.MinioClient;
import lombok.AllArgsConstructor;
import org.springblade.core.oss.props.OssProperties;
import org.springblade.core.oss.rule.OssRule;
import org.springblade.resource.core.MinioTemplate;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.web.servlet.MultipartProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@AllArgsConstructor
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(OssProperties.class)
@ConditionalOnProperty(value = "oss.name", havingValue = "minio")
public class MinIOConfig {

	private OssProperties ossProperties;

	@Bean
	@ConditionalOnMissingBean(MinioClient.class)
	public MinioClient minioClient() {
		return MinioClient.builder()
			.endpoint(ossProperties.getEndpoint())
			.credentials(ossProperties.getAccessKey(), ossProperties.getSecretKey())
			.build();
	}

	@Bean
	@ConditionalOnMissingBean(OssRule.class)
	public OssRule ossRule() {
		return new ImgOssRule();
	}

	@Bean
	@ConditionalOnMissingBean(MinioTemplate.class)
	@ConditionalOnBean({MinioClient.class, OssRule.class})
	public MinioTemplate minioTemplate(MinioClient minioClient, OssRule ossRule, MultipartProperties multipartProperties) {
		return new MinioTemplate(minioClient, ossProperties, ossRule, multipartProperties);
	}
}
